package com.quanyan.club.task.tracker;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSONObject;
import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.core.domain.Job;
import com.github.ltsopensource.tasktracker.Result;
import com.github.ltsopensource.tasktracker.runner.JobContext;
import com.github.ltsopensource.tasktracker.runner.JobRunner;
import com.quanyan.api.APIResponse;
import com.quanyan.club.entity.db.*;
import com.quanyan.club.mapper.TbActivityMapper;
import com.quanyan.club.mapper.TbClubActivityMapper;
import com.quanyan.club.mapper.TbOrderMapper;
import com.quanyan.club.mapper.TbSignUserMapper;
import com.quanyan.club.service.ActivityCRUDService;
import com.quanyan.club.service.ActivitySupportService;
import com.quanyan.club.service.ClubIntegralService;
import com.quanyan.comment.reqeust.ReqCommentDetailScore;
import com.quanyan.comment.response.RespCommentDetail;
import com.quanyan.comment.response.RespCommentTagAndCommentDetail;
import com.quanyan.comment.serviceFacade.CommentServiceFacade;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.exception.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by yue.yuan on 2016/12/15.
 */
@Service
public class ActivityAutoAppraise implements JobRunner{

    private static Logger logger = LoggerFactory.getLogger(ActivityAutoAppraise.class);

    @Autowired
    private CommentServiceFacade commentServiceFacade;
    @Autowired
    private ActivitySupportService activitySupportService;
    @Autowired
    private TbClubActivityMapper tbClubActivityMapper;
    @Autowired
    private TbActivityMapper tbActivityMapper;
    @Autowired
    private ActivityCRUDService activityCRUDService;
    @Autowired
    private TbSignUserMapper tbSignUserMapper;
    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private ClubIntegralService clubIntegralService;

    @Override
    public Result run(JobContext jobContext) throws Throwable {

        Job job = jobContext.getJob();
        if (job == null) {
            return new Result(Action.EXECUTE_EXCEPTION, "任务不存在");
        }
        Map<String, String> params = job.getExtParams();
        logger.warn("俱乐部活动结束时通知任务执行，参数：" + params);
        int activityId = Integer.parseInt(params.get("activityId"));
        String businessOrderNo = params.get("businessOrderNo");

        TbClubActivityExample clubActivityExample = new TbClubActivityExample();
        clubActivityExample.createCriteria().andActivityIdEqualTo(activityId)
                .andActivityStatusNotEqualTo(3f).andIsSettleEqualTo(Constants.BYTE_ONE)
                .andIsDeleteEqualTo(Constants.BYTE_ZERO);
        List<TbClubActivity> list =
                tbClubActivityMapper.selectByExample(clubActivityExample);
        if(null == list || list.size() != 1)
        {
            logger.warn("活动还不可评价，定时器有问题，快点核查呀！");
            return new Result(Action.EXECUTE_SUCCESS);
        }
        TbClubActivity tbClubActivity = list.get(0);
        int clubId = tbClubActivity.getClubId();
        getUnAppraiseOrder(activityId, clubId);
        return new Result(Action.EXECUTE_SUCCESS);
    }

    public void getUnAppraiseOrder(int activityId, int clubId)
    {
        TbSignUserExample signUserExample = new TbSignUserExample();
        signUserExample.createCriteria().andActivityIdEqualTo(activityId)
                .andManageTypeEqualTo(4).andStatusEqualTo(1).andIsCancelEqualTo(0)
                .andOrderUserIdIsNotNull().andOrderIdIsNotNull();
        List<TbSignUser> tbSignUsers = tbSignUserMapper.selectByExample(signUserExample);
        List<Integer> orderIds = new ArrayList<Integer>();
        if(CollectionUtils.isEmpty(tbSignUsers)) {
            logger.warn("报名人数为空");
            return;
        }
        for (TbSignUser signUser : tbSignUsers)
        {
            orderIds.add(signUser.getOrderId());
        }
        //已经支付并且签到却没有评价的
        TbOrderExample orderExample = new TbOrderExample();
        orderExample.createCriteria().andActivityIdEqualTo(activityId)
                .andOrderStatusIn(Arrays.asList((byte)2,(byte)6))
                .andCancelTypeEqualTo(Constants.BYTE_ZERO);
        List<TbOrder> orders = tbOrderMapper.selectByExample(orderExample);
        if(CollectionUtils.isEmpty(orders))
        {
            logger.warn("未评价订单为空");
            return;
        }
        APIResponse setting = activityCRUDService.getAppraiseSetting();
        RespCommentTagAndCommentDetail respCommentTagAndCommentDetail =
                (RespCommentTagAndCommentDetail)setting.getData();
        logger.warn("评价配置信息：" + JSONObject.toJSON(respCommentTagAndCommentDetail));
        List<RespCommentDetail> respCommentDetails =
                respCommentTagAndCommentDetail.getLstCommentDetail();
        List<Map<String, Object>> lstCommentDetailScore = new ArrayList<Map<String, Object>>();
        for(RespCommentDetail detail : respCommentDetails)
        {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("commentDetailId", detail.getCommentDetailId());
            map.put("score", 5d);
            lstCommentDetailScore.add(map);
        }
        for(TbOrder order : orders)
        {
            com.quanyan.comment.reqeust.ReqCommentParam reqCommentParam =
                    new com.quanyan.comment.reqeust.ReqCommentParam();
            reqCommentParam.setSystemCode(Constants.CLUB_SYSTEM_CODE);
            reqCommentParam.setBusinessCode(Constants.CLUB_ACTIVITY_COMMENT_BUSINESS_CODE);
            reqCommentParam.setAnonymous(Constants.BYTE_ONE);
            reqCommentParam.setLstCommentDetailScore(lstCommentDetailScore);
            reqCommentParam.setScore(5d);
            reqCommentParam.setCommentType(1);
            reqCommentParam.setCommentContent("默认评价！");
            reqCommentParam.setFromUserId(order.getOrderUid());
            reqCommentParam.setBusinessId(activityId);
            reqCommentParam.setCommonParam(clubId);
            logger.warn("开始调用评论系统，入参：{}" + JSONObject.toJSONString(reqCommentParam));
            APIResponse apiResponse = commentServiceFacade.commentAdd(reqCommentParam);
            if (!apiResponse.isRet()) {
                logger.error("调用评论系统失败, 失败信息: " + apiResponse.getErrmsg());
                continue;
            }
            logger.warn("开始调用积分，入参：clubId" + clubId + "addScore:" + 5);
            clubIntegralService.modifyClubCommentStar(clubId, 5);
            TbOrder tbOrder = new TbOrder();
            tbOrder.setId(order.getId());
            tbOrder.setOrderStatus((byte)7);
            tbOrderMapper.updateByPrimaryKeySelective(tbOrder);
        }
        return;
    }
}
